<template>
  <div class="wrapper" ref="wrapperEl">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>商家钱包</p>
    </header>
    <section class="wallet-info" v-if="wallet">
      <div class="balance">
        <div class="balance-value">总余额：{{ formatCurrency(wallet.balance) }}</div>
        <div class="balance-breakdown">
          个人余额：{{ formatCurrency(personalBalance) }} + 奖励金额：{{ formatCurrency(wallet.rewardAmount) }}
        </div>
        <div class="balance-sub">
          冻结资金 {{ formatCurrency(wallet.frozenAmount) }}
          <span v-if="wallet.incomingFrozenAmount && wallet.incomingFrozenAmount > 0" class="incoming-tip">
            · 待入账 {{ formatCurrency(wallet.incomingFrozenAmount) }}
          </span>
        </div>
      </div>
      <div class="actions-grid">
        <div class="action" @click="navigateWithLoading('/wallet/recharge')">
          <i class="fa fa-credit-card"></i>
          <span>充值</span>
        </div>
        <div class="action" @click="navigateWithLoading('/wallet/withdraw')">
          <i class="fa fa-download"></i>
          <span>提现</span>
        </div>
        <div class="action" @click="navigateWithLoading('/wallet/transactions')">
          <i class="fa fa-list"></i>
          <span>交易记录</span>
        </div>
      </div>
      
      <!-- 冻结资金说明 -->
      <div class="freeze-info" v-if="wallet.frozenAmount && wallet.frozenAmount > 0">
        <div class="info-header">
          <i class="fa fa-info-circle"></i>
          <span>冻结资金说明</span>
        </div>
        <p>您有 <strong>{{ formatCurrency(wallet.frozenAmount) }}</strong> 的资金处于冻结状态。</p>
        <p>这是顾客已支付但尚未确认收货的订单金额，确认收货后将自动解冻到可用余额。</p>
      </div>
    </section>
    <section class="recent">
      <div class="section-title">
        <span>最近交易</span>
        <div class="section-actions">
          <span class="link" @click="toTransactions">查看全部</span>
          <span class="link" @click="refresh">刷新</span>
        </div>
      </div>
      <div class="pull" v-show="pullStatus!=='idle'">{{ pullText }}</div>
      <ul class="list">
        <li v-for="t in recent" :key="t.id" class="item">
          <div class="left">
            <div class="type">{{ typeName(t.type) }}</div>
            <div class="time">{{ displayTime(t.createTime) }}</div>
          </div>
          <div class="right" :class="amountClass(t.amount)">{{ formatCurrency(t.amount) }}</div>
        </li>
      </ul>
      <div class="more">
        <button @click="loadMore" :disabled="loadingMore">{{ loadingMore? '加载中...' : '加载更多' }}</button>
      </div>
      <div v-if="errorMsg" class="error">{{ errorMsg }}</div>
      <div v-if="errorMsg && errorMsg.includes('钱包不存在')" class="fix">
        <button class="primary" @click="createWallet">创建钱包</button>
      </div>
      <div v-if="!recent.length && !errorMsg" class="empty">暂无交易</div>
    </section>
    <div class="overlay" v-show="navigating">
      <div class="spinner"></div>
      <div class="overlay-text">处理中...</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { walletApi, userApi } from '../api'

const router = useRouter()
const currentUser = ref(null)
const wallet = ref(null)
const recent = ref([])
const pageIndex = ref(0)
const loadingMore = ref(false)
const errorMsg = ref('')
const navigating = ref(false)
const wrapperEl = ref(null)
const pullStatus = ref('idle')
const startY = ref(0)

const load = async () => {
  errorMsg.value = ''
  try {
    // 获取用户信息和钱包信息
    const [user, w] = await Promise.all([
      userApi.getCurrentUser(),
      walletApi.getMyWallet()
    ])
    currentUser.value = user
    wallet.value = w
    const page = await walletApi.listTransactions({ page: 0, size: 10, sort: 'createTime,desc' })
    recent.value = Array.isArray(page?.content) ? page.content : []
    pageIndex.value = 0
  } catch (e) {
    errorMsg.value = e.message || '加载失败'
  }
}

const refresh = async () => {
  pullStatus.value = 'refreshing'
  await load()
  pullStatus.value = 'idle'
}

const loadMore = async () => {
  loadingMore.value = true
  try {
    const next = pageIndex.value + 1
    const page = await walletApi.listTransactions({ page: next, size: 10, sort: 'createTime,desc' })
    const arr = Array.isArray(page?.content) ? page.content : []
    if (arr.length) {
      recent.value = recent.value.concat(arr)
      pageIndex.value = next
    }
  } catch (e) {
    errorMsg.value = e.message || '加载失败'
  } finally {
    loadingMore.value = false
  }
}

onMounted(() => {
  load()
  const el = wrapperEl.value
  el.addEventListener('touchstart', e => { startY.value = e.touches[0].clientY; pullStatus.value = 'idle' })
  el.addEventListener('touchmove', e => {
    const dy = e.touches[0].clientY - startY.value
    if (dy > 60 && document.documentElement.scrollTop === 0) pullStatus.value = 'pulling'
  })
  el.addEventListener('touchend', async () => { if (pullStatus.value === 'pulling') await refresh() })
})

const navigateWithLoading = async path => { navigating.value = true; setTimeout(() => { router.push(path); navigating.value = false }, 500) }
const toTransactions = () => router.push('/wallet/transactions')
const goBack = () => router.push('/businessManage')

const formatCurrency = v => {
  const n = Number(v || 0)
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + '元'
}
const amountClass = v => Number(v) >= 0 ? 'pos' : 'neg'
const typeName = t => {
  const map = { 
    DEPOSIT:'充值', 
    WITHDRAW:'提现', 
    PAYMENT:'支付', 
    TRANSFER_IN:'转入', 
    TRANSFER_OUT:'转出', 
    FREEZE:'冻结', 
    UNFREEZE:'解冻', 
    REFUND:'退款', 
    REALIZE_INCOME:'已实现收益',
    OVERDRAFT_REPAY:'花呗还款',
    OVERDRAFT_REPAYMENT:'花呗还款',
    OVERDRAFT_PAY:'花呗支付',
    INCOME_FREEZE:'入账预冻结',
    REALIZE_TO_FROZEN:'转为实际冻结'
  }
  return map[t] || t
}
const displayTime = t => typeof t === 'string' ? t.replace('T',' ') : t

// 计算个人余额（总余额 - 奖励金额）
const personalBalance = computed(() => {
  if (!wallet.value) return 0
  return Number(wallet.value.balance || 0) - Number(wallet.value.rewardAmount || 0)
})

const createWallet = async () => {
  try {
    navigating.value = true
    await walletApi.createWallet()
    await load()
  } catch (e) {
    errorMsg.value = e.message || '创建失败'
  } finally {
    navigating.value = false
  }
}

const pullText = computed(() => {
  return pullStatus.value === 'pulling' ? '下拉刷新' : pullStatus.value === 'refreshing' ? '刷新中...' : ''
})
</script>

<style scoped>
.wrapper { width: 100%; min-height: 100vh; background-color: #f5f5f5; padding-bottom: 2vw; }
header { width: 100%; height: 12vw; background-color: #0097ff; color: #fff; font-size: 4.8vw; position: fixed; left: 0; top: 0; z-index: 1000; display: flex; justify-content: center; align-items: center; }
header i { position: absolute; left: 3vw; font-size: 6vw; color: #fff; cursor: pointer; }
.wallet-info { margin-top: 14vw; padding: 4vw; }
.balance { background: #fff; border-radius: 2vw; padding: 4vw; box-shadow: 0 2px 8px rgba(0,0,0,0.06); }
.balance-value { font-size: 6vw; font-weight: 800; color: #333; }
.balance-breakdown { margin-top: 1.5vw; font-size: 3.6vw; color: #666; font-weight: 500; }
.balance-sub { margin-top: 2vw; font-size: 3.4vw; color: #666; }
.incoming-tip { color: #ff9800; font-weight: 600; }
.actions-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 3vw; margin-top: 4vw; }
.action { background: #f7f9ff; border-radius: 2vw; padding: 3vw; text-align: center; cursor: pointer; transition: transform .15s ease, background .2s ease; }
.action:hover { background: #eef3ff; transform: translateY(-2px); }
.action i { font-size: 6vw; color: #0097ff; display: block; }
.action span { display: block; margin-top: 2vw; font-size: 3.6vw; color: #333; }

/* 冻结资金说明 */
.freeze-info { background: #fff3cd; border: 1px solid #ffc107; border-radius: 2vw; padding: 3vw; margin-top: 3vw; }
.info-header { display: flex; align-items: center; gap: 1vw; font-size: 3.8vw; font-weight: 600; color: #856404; margin-bottom: 1.5vw; }
.info-header i { font-size: 4vw; }
.freeze-info p { font-size: 3.4vw; color: #856404; line-height: 1.6; margin: 1vw 0; }
.freeze-info strong { color: #ff6b35; font-weight: 700; }

.recent { padding: 4vw; }
.section-title { display: flex; justify-content: space-between; font-size: 4vw; color: #666; align-items: center; margin-bottom: 3vw; }
.section-actions { display: flex; gap: 4vw; }
.section-title .link { color: #0097ff; cursor: pointer; font-size: 3.4vw; }
.pull { text-align: center; color: #999; font-size: 3.2vw; padding: 2vw 0; }
.list { list-style: none; margin: 0; padding: 0; background: #fff; border-radius: 2vw; }
.item { display: flex; justify-content: space-between; align-items: center; padding: 3vw 4vw; border-bottom: 1px solid #f5f5f5; }
.item:last-child { border-bottom: none; }
.left .type { font-size: 4vw; color: #333; font-weight: 500; }
.left .time { font-size: 3vw; color: #999; margin-top: 1vw; }
.right { font-size: 4vw; font-weight: 700; }
.right.pos { color: #38ca73; }
.right.neg { color: #ff6b35; }
.more { display: flex; justify-content: center; margin-top: 3vw; }
.more button { height: 10vw; border: none; border-radius: 2vw; padding: 0 6vw; background: #0097ff; color: #fff; font-size: 3.8vw; cursor: pointer; }
.more button:disabled { background: #ccc; cursor: not-allowed; }
.error { margin-top: 3vw; color: #ff5252; font-size: 3.6vw; text-align: center; padding: 3vw; background: #fff; border-radius: 2vw; }
.fix { display: flex; justify-content: center; margin-top: 3vw; }
.primary { height: 10vw; border: none; border-radius: 2vw; padding: 0 6vw; background: #38ca73; color: #fff; font-size: 3.8vw; cursor: pointer; }
.empty { padding: 6vw; text-align: center; color: #999; background: #fff; border-radius: 2vw; }
.overlay { position: fixed; left:0; top:0; right:0; bottom:0; background: rgba(0,0,0,.35); display: flex; flex-direction: column; justify-content: center; align-items: center; z-index: 2000; }
.spinner { width: 8vw; height: 8vw; border: 1vw solid #fff; border-top-color: #0097ff; border-radius: 50%; animation: spin 1s linear infinite; }
.overlay-text { color: #fff; margin-top: 2vw; font-size: 4vw; }
@keyframes spin { to { transform: rotate(360deg) } }
</style>

